<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handlePull"
          >拉取</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="name"
        label="分类名称"
        width="260"
      ></el-table-column>
      <el-table-column
        prop="showLevel"
        label="等级"
        width="200"
      ></el-table-column>
      <el-table-column prop="imgUrl" label="缩略图" width="200">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.imgUrl"
            fit="fill"
            style="width: 50px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          {{ scope.row.sort ? scope.row.sort : 0 }}
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSort(scope.row)"
            v-hasPermi="['commodity:category:changeSort']"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否在用户端展示" prop="isShowUserHome">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShowUserHome"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowUser(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否在pc端展示" prop="isShowPcHome">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShowPcHome"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowPc(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否在pc菜单" prop="isIndexPcMenu">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isIndexPcMenu"
            :active-value="1"
            :inactive-value="0"
            @change="handleShowPcMenu(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecommend(scope.row)"
            v-hasPermi="['commodity:category:isShowRecommend']"
            >推荐管理</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['commodity:category:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:category:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 推荐管理 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="是否在推荐中展示" prop="isShowRecommend">
          <el-radio-group v-model="form.isShowRecommend">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类背景图" prop="recommendImg">
          <Image-Upload
            :value="form.recommendImg"
            :limit="1"
            @input="getImgUrl"
          ></Image-Upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      :title="newTitle"
      :visible.sync="isEdit"
      width="600px"
      append-to-body
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="125px"
      >
        <el-form-item label="商品分类名称" prop="name">
          <el-input
            v-model="editForm.name"
            :disabled="isAdd"
            placeholder="请输入商品分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类图片" prop="mallImgUrl">
          <Image-Upload
            :value="editForm.mallImgUrl"
            :limit="1"
            @input="getImgUrlEdit"
          ></Image-Upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
        <el-button @click="isEdit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改排序 -->
    <el-dialog title="修改排序" :visible.sync="isSort" width="400px">
      <el-form
        :model="sortForm"
        ref="sort"
        :rules="sortRule"
        label-width="80px"
      >
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="sortForm.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSort">确 定</el-button>
        <el-button @click="isSort = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 拉取 -->
    <el-dialog
      title="拉取分类"
      :visible.sync="pullOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="reForm" :model="pullForm" label-width="125px">
        <el-form-item label="本地分类">
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="false"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPull" :loading="pullLoad"
          >确 定</el-button
        >
        <el-button @click="pullOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  showAllCategory,
  changeShowUserHome,
  changeShowPcHome,
  changeShowRecommend,
  changeSort,
  changeIndexPcMenu,
  getMallProductCategory,
  updateMallProductCategory,
  showTreeProductCate,
  addAllProductCate,
} from "@/api/product/category";
import { deletePriCate } from "@/api/company/category";
export default {
  name: "Category",
  data() {
    return {
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      pullForm: {},
      pullOpen: false,
      pullLoad: false,
      isEdit: false,
      newTitle: "新增分类",
      editForm: {},
      editRules: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示修改排序弹出层
      isSort: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      //修改排序
      sortForm: {
        sort: null,
      },
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //排序校验
      sortRule: {
        sort: [
          {
            required: true,
            message: "请输入排序",
            trriger: "blur",
            type: "number",
          },
        ],
      },
      editRules: {
        isShowUserHome: [
          {
            required: true,
            message: "请选择是否在用户端展示",
            trriger: "change",
            type: "number",
          },
        ],
        isShowPcHome: [
          {
            required: true,
            message: "请选择是否在pc端展示",
            trriger: "change",
            type: "number",
          },
        ],
        isIndexPcMenu: [
          {
            required: true,
            message: "请选择是否展示首页菜单分类",
            trriger: "change",
            type: "number",
          },
        ],
        useType: [
          {
            required: true,
            message: "请选择分类图片展示方式",
            trriger: "change",
            type: "number",
          },
        ],
      },
      isAdd: false,
    };
  },
  created() {
    this.getList();
  },

  methods: {
    // 提交拉取
    submitPull() {
      const cateList = this.getMenuAllCheckedKeys();
      const pushData = { isGift: 0, cateList };
      this.pullLoad = true;
      addAllProductCate(pushData).then((res) => {
        this.pullLoad = false;
        this.$modal.msgSuccess("拉取成功");
        this.pullOpen = false;
        this.getList();
      });
    },
    // 拉取弹窗
    handlePull() {
      this.pullOpen = true;
      this.getProductCateTree();
    },
    /** 查询菜单树结构 */
    getProductCateTree() {
      showTreeProductCate().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();

      const cate = this.$refs.menu.getCheckedNodes();
      let halfCheckedNodes = this.$refs.menu.getHalfCheckedNodes();
      cate.unshift.apply(cate, halfCheckedNodes);
      const sendCate = cate.map((v) => {
        const { id, parentId } = v;
        return { id, parentId };
      });
      return sendCate;
      // 半选中的菜单节点
      // let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      // return checkedKeys;
    },

    //修改排序
    handleSort(row) {
      this.isSort = true;
      this.sortForm = {
        sort: row.sort ? row.sort : 0,
        productCategoryId: row.id,
      };
    },
    //编辑
    handleEdit(row) {
      const { id } = row;
      this.isEdit = true;
      this.newTitle = "修改分类";
      getMallProductCategory(id).then((res) => {
        this.editForm = {
          id: res.data.id,
          productCategoryId: res.data.id,
          mallImgUrl: res.data.mallImgUrl,
          name: res.data.name,
          isShowUserHome: res.data.isShowUserHome,
          isShowPcHome: res.data.isShowPcHome,
          isIndexPcMenu: res.data.isIndexPcMenu,
          useType: res.data.useType,
        };
      });
    },
    //修改排序提交
    submitFormSort() {
      this.$refs["sort"].validate((valid) => {
        if (valid) {
          changeSort(this.sortForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isSort = false;
            this.getList();
          });
        }
      });
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      showAllCategory(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, "productCategoryId");
        this.loading = false;
      });
    },
    getImgUrl(e) {
      this.form.recommendImg = e;
    },
    getImgUrlEdit(e) {
      this.editForm.mallImgUrl = e;
    },
    //是否pc菜单
    handleShowPcMenu(row) {
      const { id: productCategoryId, isIndexPcMenu } = row;

      let text = row.isIndexPcMenu == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "pc端菜单吗？")
        .then(function () {
          return changeIndexPcMenu({ productCategoryId, isIndexPcMenu });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isIndexPcMenu = row.isIndexPcMenu == 1 ? 0 : 1;
        });
    },
    //是否再用户端展示开关
    handleShowUser(row) {
      const { id: productCategoryId, isShowUserHome } = row;

      let text = row.isShowUserHome == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "用户端展示吗？")
        .then(function () {
          return changeShowUserHome({ productCategoryId, isShowUserHome });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShowUserHome = row.isShowUserHome == 1 ? 0 : 1;
        });
    },
    //是否在pc端展示开关
    handleShowPc(row) {
      const { id: productCategoryId, isShowPcHome } = row;

      let text = row.isShowPcHome == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "用户端展示吗？")
        .then(function () {
          return changeShowPcHome({ productCategoryId, isShowPcHome });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShowPcHome = row.isShowPcHome == 1 ? 0 : 1;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        isShowRecommend: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleRecommend(row) {
      this.reset();
      this.open = true;
      this.form.productCategoryId = row.id;
      this.form.isShowRecommend = row.isShowRecommend;
      this.form.recommendImg = row.recommendImg;
      this.title = "推荐管理";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 提交编辑
    submitEditForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          updateMallProductCategory(this.editForm).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.isEdit = false;
            this.getList();
          });
        }
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          changeShowRecommend(this.form).then((response) => {
            this.$modal.msgSuccess("设置成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的数据项？')
        .then(function () {
          return deletePriCate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
};
</script>
